package com.gmlive.common.sample

import android.app.Application
import android.os.Build
import android.util.Log
import coil.ImageLoader
import coil.ImageLoaderFactory
import coil.util.DebugLogger
import com.gmlive.svgaplayer.util.ResponseHeaderInterceptor
import com.gmlive.svgaplayer.util.forceTls12
import com.gmlive.svgaplayer.util.ignoreVerify
import com.gmlive.svgaplayer.util.setupSSLFactory
import okhttp3.Cache
import okhttp3.Dispatcher
import okhttp3.OkHttpClient
import java.io.File

/**

 * @Author svenj
 * @Date 2021/1/25
 * @Email svenjzm@gmail.com
 */
class DefaultImageLoaderFactory(private val application: Application): ImageLoaderFactory {
    override fun newImageLoader(): ImageLoader {
        return ImageLoader.Builder(application)
                .availableMemoryPercentage(0.25) // Use 25% of the application's available memory.
                .crossfade(true) // Show a short crossfade when loading images from network or disk.
                .okHttpClient {
                    // Create a disk cache with "unlimited" size. Don't do this in production.
                    // To create the an optimized Coil disk cache, use CoilUtils.createDefaultCache(context).
                    val cacheDirectory = File(application.filesDir, "image_cache").apply { mkdirs() }
                    val cache = Cache(cacheDirectory, Long.MAX_VALUE)

                    // Rewrite the Cache-Control header to cache all responses for a year.
                    val cacheControlInterceptor = ResponseHeaderInterceptor("Cache-Control", "max-age=31536000,public")

                    // Don't limit concurrent network requests by host.
                    val dispatcher = Dispatcher().apply { maxRequestsPerHost = maxRequests }

                    // Lazily create the OkHttpClient that is used for network operations.
                    OkHttpClient.Builder()
                            .cache(cache)
                            .dispatcher(dispatcher)
                            .ignoreVerify()
                            .setupSSLFactory()
                            .forceTls12() // The Unsplash API requires TLS 1.2, which isn't enabled by default before API 21.
                            .addNetworkInterceptor(cacheControlInterceptor)
                            .build()
                }
                .apply {
                    // Enable logging to the standard Android log if this is a debug build.
                    if (BuildConfig.DEBUG) {
                        logger(DebugLogger(Log.VERBOSE))
                    }
                }
                .build()
    }
}